package com.jack.uikit.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.widget.Toolbar
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SizeUtils
import com.jack.uikit.R
import com.jack.uikit.expand.signClick
import kotlinx.android.synthetic.main.layout_titlebar.view.*

class TitleBar : Toolbar {
    var onLeftClick: ((v: View) -> Unit)? = null
    var onRightClick: ((v: View) -> Unit)? = null

    constructor(context: Context) : this(context, null)

    @SuppressLint("RestrictedApi")
    constructor(context: Context, attributeSet: AttributeSet?) : super(context, attributeSet) {
        LayoutInflater.from(context).inflate(R.layout.layout_titlebar, this)
        setContentInsetsRelative(SizeUtils.dp2px(0f), SizeUtils.dp2px(0f))
        val padding = SizeUtils.dp2px(14f)
        setPadding(
            paddingLeft + padding,
            paddingTop + padding + BarUtils.getStatusBarHeight(),
            paddingRight + padding,
            paddingBottom + padding)
        val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.TitleBar)
        val backDrwable = typedArray.getDrawable(R.styleable.TitleBar_left_icon)
        ivBack.setImageDrawable(backDrwable)
        tvTitle.text = title
        title = ""
        val titleSize = typedArray.getDimension(R.styleable.TitleBar_title_size,
            SizeUtils.sp2px(18f).toFloat())
        tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize)
        val titleColor = typedArray.getColor(R.styleable.TitleBar_title_color, Color.BLACK)
        tvTitle.setTextColor(titleColor)
        val rightDrawable = typedArray.getDrawable(R.styleable.TitleBar_right_icon)
        ivRight.setImageDrawable(rightDrawable)
        typedArray.recycle()

        ivBack.signClick {
            onLeftClick?.invoke(it)
        }

        ivRight.signClick {
            onRightClick?.invoke(it)
        }

    }

}